package gw.com.android.ui.onlive;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.ChatTokenRequest;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.Https;
import gw.com.android.ui.me.PhoneNumber;
import gw.com.android.ui.me.ProfileData;
import gw.com.android.ui.me.ProfileRequest;
import gw.com.android.utils.ENV;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.util.DeviceUtil;

/**
 * @author jett
 * @since 2018-03-08.
 */
class DiscussAddRequest {

    private final String content;
    private final boolean isAnalyst;        //  是否是分析师
    private String analystNo;    //  分析师的账号（hxbj这种）
    private final boolean isShowTrade;      //  是否是晒单 。true晒单，false帖子；一键晒单为晒单，其它地方为帖子
    private List<File> fileList;
    private final OnDiscussCallback callback;

    DiscussAddRequest(String content, boolean isAnalyst, String analystNo, boolean isShowTrade, List<File> fileList, OnDiscussCallback callback) {
        this.content = content;
        this.isAnalyst = isAnalyst;
        this.analystNo = analystNo;
        this.isShowTrade = isShowTrade;
        this.fileList = fileList;
        this.callback = callback;
    }

    void execute(final String imgSize) {
        if (fileList == null || fileList.size() == 0) return;
        for (int i = 0; i < fileList.size(); i++) {// 检查list中的图片是不是都存在
            if (!fileList.get(i).exists()) {
                postFailure();
                return;
            }
        }

        String uploadUrl = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/upload/uploadFile";
        Https https = new Https().url(uploadUrl)
                .addParam("platform", "android")
                .addParam("fileDir", "pic/trade/chat/front")
                .addParam("fileType", "showTrade")
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_COMPANY_ID_TAG));

        for (int i = 0; i < fileList.size(); i++) {// 循环添加文件
            https = https.addUploadFile("file", null, fileList.get(i));

        }
        https.upload(new Https.UploadListener<String>() {
            @Override
            public void onUploading(long current, long total, boolean done) {
            }

            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                String serverUrl = parseUploadResponse(result);//上传完成之后，取返回的serverUrl
                if (TextUtils.isEmpty(serverUrl)) {//如果serverUrl是空
                    postFailure();//那么弹出错误提示
                    return;
                }
                acquirePhone(serverUrl, imgSize);//如果不是空，才进行晒单数据的上传
            }

            @Override
            public void onFailure(Request request, IOException e) {
                if (callback != null) {
                    callback.onFailure();
                }
            }
        });
    }

    private void acquirePhone(final String serverUrl, final String imgSize) {
        PhoneNumber.getInstance().acquireAsync(new PhoneNumber.OnPhoneListener() {
            @Override
            public void onSuccess(final String num) {
                //这里要插入一个步骤，获取token，再真正去发请求
                acquireChatToken(new ChatTokenRequest.OnTokenListener() {
                    @Override
                    public void onSuccess(String token) {
                        getProfile(num, token, serverUrl, imgSize);
                    }

                    @Override
                    public void onFailure(Exception e) {
                        postFailure();
                    }
                });

            }

            @Override
            public void onFailure() {
                postFailure();
            }
        });
    }

    private void acquireChatToken(ChatTokenRequest.OnTokenListener listener) {
        new ChatTokenRequest().acquire(listener);
    }

    private void getProfile(final String mobilePhone, final String token, final String serverUrl, final String imgSize) {
        ProfileRequest profileRequest = new ProfileRequest();
        final ProfileData data = profileRequest.fetchLocal();
        if (data != null) {
            sendDiscuss(mobilePhone, token, serverUrl, imgSize, data.nickname, data.avatar);
        } else {
            profileRequest.getUserInfo(mobilePhone, new HttpCallback<ProfileData>() {
                @Override
                public void onSuccess(ProfileData result) {
                    if (result == null) {
                        sendDiscuss(mobilePhone, token, serverUrl, imgSize, null, null);
                    } else {
                        sendDiscuss(mobilePhone, token, serverUrl, imgSize, result.nickname, result.avatar);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    postFailure();
                }
            });
        }
    }

    private void sendDiscuss(String mobilePhone, String token, String serverUrl, String imgSize, String userName, String avatar) {
        if (TextUtils.isEmpty(avatar)) {
            avatar = ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_USER_IMAGE);
        }
        if (TextUtils.isEmpty(userName)){
            userName = GTConfig.instance().mCurName;
        }
        String discussUrl = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/showTrade/addShowTrade";
        Log.d("sendDiscussTag", "1");
        String realContent;
        if (ENV.isUat()) {
            realContent = "(AndroidClient) - " + content;
        } else {
            realContent = content;
        }
        // userNo 是必传字段，不是分析师发贴时，没有userNo，就传手机号
        analystNo = TextUtils.isEmpty(analystNo) ? mobilePhone : analystNo;
        Https https = new Https().url(discussUrl)
                .addParam("token", token)
                .addParam("platform", "android")
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("groupType", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_GROUP_TYPE))
                .addParam("userNo", analystNo)
                .addParam("avatar", avatar)
                .addParam("userName", userName)
                .addParam("telePhone", mobilePhone)
                .addParam("tradeImg", serverUrl)
                .addParam("imgSize", imgSize)
                .addParam("remark", realContent == null ? "" : realContent)
                .addParam("Ip", DeviceUtil.instance().getMacAddr(AppMain.getApp()))
//                .addParam("mTitle", null)
                .addParam("tradeType", isAnalyst ? "1" : "2") //  类别 1 分析师晒单，2 客户晒单
                .addParam("type", isShowTrade ? "0" : "1")      //  类型：0 晒单（默认）， 1 帖子
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_COMPANY_ID_TAG))
                .addParam("accountNo", GTConfig.instance().mCurName);//这里的accountNo是在发帖用户是分析师的情况下，用于保存分析师的账号（hxbj这种）

        //遍历参数
        Map<String, String> map = https.getParam();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Log.d("discussAddHttpParamTag", entry.getKey() + ":" + entry.getValue());
        }

        https.post(new Https.ResponseCallback<String>() {
            @Override
            public void onSuccess(Request request, Response response, String result, int code) {
                if (callback == null) {
                    return;
                }
                if (parseDiscussResponse(result)) {
                    postSuccess();
                } else {
                    postFailure();
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                postFailure();
            }
        });
    }

    private void postSuccess() {
        if (callback != null) {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                callback.onSuccess();
            } else {
                AppMain.getApp().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSuccess();
                    }
                });
            }
        }
    }

    private void postFailure() {
        if (callback != null) {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                callback.onFailure();
            } else {
                AppMain.getApp().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure();
                    }
                });
            }
        }
    }

    private static String parseUploadResponse(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONArray dataArr = jsonObject.optJSONArray("data");
            if (dataArr == null || dataArr.length() < 0) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dataArr.length(); i++) {
                JSONObject data = dataArr.optJSONObject(i);
                if (data != null) {
                    String host = data.optString("fileDomain");
                    String path = data.optString("filePath");
                    sb.append(host).append(path).append(",");
                }
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            return sb.toString();
        } catch (JSONException ignore) {
        }
        return null;
    }

    private static boolean parseDiscussResponse(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                return dataJson.optBoolean("isOK", false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public interface OnDiscussCallback {

        void onSuccess();

        void onFailure();

    }

}
